package com.kehao.leetcode.basic.linkedList;




public class LinkedListSolution2 {

    class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

    public ListNode removeNthFromEnd(ListNode head, int n) {
        if(head.next == null){
            return null;
        }
        ListNode node1 = head;
        ListNode node2 = head;
        for (int i = 0; i < n; i++) {
            node2 = node2.next;
        }
        if(node2 == null){
            return node1.next;
        }
        while (node2.next!=null){
            node2 = node2.next;
            node1 = node1.next;
        }

        node1.next = node1.next.next;
        return head;
    }
}

